<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div class="dashboard-container">
    <el-container>
      <el-header class="header">
        <div class="header-left">
          <span class="logo">卡密管理系统</span>
        </div>
        <div class="header-right">
          <el-dropdown trigger="click">
            <span class="user-info">
              <User class="user-icon" />
              <span>管理员</span>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="handleLogout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>
      <el-container>
        <el-aside width="200px" class="sidebar">
          <el-menu :default-openeds="['1']" router>
            <el-sub-menu index="1">
              <template #title>
                <DashboardIcon class="menu-icon" />
                <span>仪表盘</span>
              </template>
              <el-menu-item index="/dashboard">
                <span>数据统计</span>
              </el-menu-item>
            </el-sub-menu>
            <el-sub-menu index="2">
              <template #title>
                <Key class="menu-icon" />
                <span>卡密管理</span>
              </template>
              <el-menu-item index="/generate">
                <span>生成卡密</span>
              </el-menu-item>
              <el-menu-item index="/keys">
                <span>卡密列表</span>
              </el-menu-item>
            </el-sub-menu>
          </el-menu>
        </el-aside>
        <el-main class="main-content">
          <el-card class="stat-card">
            <template #header>
              <div class="card-header">
                <span>数据统计</span>
              </div>
            </template>
            <div class="stat-container">
              <div class="stat-item">
                <div class="stat-label">总卡密数</div>
                <div class="stat-value">{{ totalKeys }}</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">已激活卡密</div>
                <div class="stat-value">{{ activatedKeys }}</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">未激活卡密</div>
                <div class="stat-value">{{ totalKeys - activatedKeys }}</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">已过期卡密</div>
                <div class="stat-value">{{ expiredKeys }}</div>
              </div>
            </div>
          </el-card>
          <el-card class="app-stat-card">
            <template #header>
              <div class="card-header">
                <span>应用卡密统计</span>
              </div>
            </template>
            <el-table :data="appStats" style="width: 100%">
              <el-table-column prop="name" label="应用名称" width="180" />
              <el-table-column prop="total" label="总卡密数" width="180" />
              <el-table-column prop="activated" label="已激活" width="180" />
              <el-table-column prop="unactivated" label="未激活" width="180" />
              <el-table-column label="操作" width="150">
                <template #default="scope">
                  <el-button type="primary" size="small" @click="viewAppKeys(scope.row.id)">
                    查看详情
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import { defineOptions } from 'vue'

defineOptions({
  name: 'DashboardView'
})

// eslint-disable-next-line vue/multi-word-component-names
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { User, DashboardIcon, Key } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const router = useRouter()
const totalKeys = ref(0)
const activatedKeys = ref(0)
const expiredKeys = ref(0)
const appStats = ref([])

// 加载仪表盘数据
const loadDashboardData = async () => {
  try {
    // 从localStorage获取token
    const token = localStorage.getItem('token')
    if (!token) {
      router.push('/login')
      return
    }

    // 调用后端API
    const response = await axios.get('/api/dashboard', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    if (response.data.success) {
      const data = response.data.data
      totalKeys.value = data.total_keys
      activatedKeys.value = data.activated_keys
      expiredKeys.value = data.expired_keys
      appStats.value = data.app_stats
    } else {
      ElMessage.error(response.data.message || '加载数据失败')
    }
  } catch (error) {
    ElMessage.error('网络错误，请稍后重试')
    console.error('Failed to load dashboard data:', error)
  }
}

const handleLogout = () => {
  localStorage.removeItem('token')
  ElMessage.success('退出成功')
  router.push('/login')
}

const viewAppKeys = (appId) => {
  router.push({ path: '/keys', query: { appId } })
}

onMounted(() => {
  loadDashboardData()
})
</script>

<style scoped>
.dashboard-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}
.header {
  background-color: #409eff;
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  height: 60px;
}
.logo {
  font-size: 20px;
  font-weight: bold;
}
.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
}
.user-icon {
  margin-right: 5px;
}
.sidebar {
  background-color: #f0f2f5;
  padding-top: 20px;
}
.menu-icon {
  margin-right: 10px;
}
.main-content {
  padding: 20px;
  background-color: #f5f7fa;
  overflow-y: auto;
  flex: 1;
}
.stat-card {
  margin-bottom: 20px;
}
.card-header {
  font-size: 16px;
  font-weight: bold;
}
.stat-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-top: 20px;
}
.stat-item {
  flex: 1 1 200px;
  background-color: #f0f2f5;
  padding: 20px;
  border-radius: 5px;
  text-align: center;
}
.stat-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}
.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
}
.app-stat-card {
  margin-bottom: 20px;
}
</style>